import api from '@/store/api';
import { useGlobalStore } from '@/store/global';
import i18n from '@/i18n';
const { t } = i18n.global as any;
/**
 * Watch for serverStatus changes in GlobalStore module
 * to set isOperationInProgress state
 * Stop watching status changes and resolve Promise when
 * serverStatus value matches passed argument or after 5 minutes
 * @param {string} serverStatus
 * @returns {Promise}
 */
const checkForServerStatus = function (serverStatus: any) {
  return new Promise<void>((resolve) => {
    const timer = setTimeout(() => {
      resolve();
      unwatch();
    }, 300000 /*5mins*/);
    const timer2 = setInterval(() => {
      useGlobalStore().getSystemInfo();
    }, 1000);
    const unwatch = watch(
      () => useGlobalStore().serverStatus,
      (value: any) => {
        if (value === serverStatus) {
          resolve();
          unwatch();
          clearTimeout(timer);
          clearInterval(timer2);
        }
      },
    );
  });
};

export const useControlStore = defineStore('control', () => {
  const isOperationInProgress = ref(false);
  const lastPowerOperationTime = ref(null);
  const lastBmcRebootTime = ref(null);

  const setOperationInProgress = (inProgress: any) =>
    (isOperationInProgress.value = inProgress);
  const setLastPowerOperationTime = (OperationTime: any) =>
    (lastPowerOperationTime.value = OperationTime);
  const setLastBmcRebootTime = (BmcRebootTime: any) =>
    (lastBmcRebootTime.value = BmcRebootTime);

  const getLastPowerOperationTime = async () => {
    return await api
      .get('/redfish/v1/Systems/system')
      .then((response) => {
        const lastReset = response.data.LastResetTime;
        if (lastReset) {
          const lastPowerOperationTime = new Date(lastReset);
          setLastPowerOperationTime(lastPowerOperationTime);
        }
      })
      .catch((error) => console.log(error));
  };
  const getLastBmcRebootTime = async () => {
    return api
      .get('/redfish/v1/Managers/bmc')
      .then((response) => {
        const lastBmcReset = response.data.LastResetTime;
        const lastBmcRebootTime = new Date(lastBmcReset);
        setLastBmcRebootTime(lastBmcRebootTime);
      })
      .catch((error) => console.log(error));
  };
  const rebootBmc = async () => {
    const data = { ResetType: 'GracefulRestart' };
    return await api
      .post('/redfish/v1/Managers/bmc/Actions/Manager.Reset', data, undefined)
      .then(() => getLastBmcRebootTime())
      .then(() => t('pageRebootBmc.toast.successRebootStart'))
      .catch((error) => {
        console.log(error);
        throw new Error(t('pageRebootBmc.toast.errorRebootStart') as string);
      });
  };
  const serverPowerOn = async () => {
    const data = { ResetType: 'On' };
    serverPowerChange(data);
    await checkForServerStatus.bind(this, 'on')();
    setOperationInProgress(false);
    getLastPowerOperationTime();
  };
  const serverSoftReboot = async () => {
    const data = { ResetType: 'GracefulRestart' };
    serverPowerChange(data);
    await checkForServerStatus.bind(this, 'on')();
    setOperationInProgress(false);
    getLastPowerOperationTime();
  };
  const serverHardReboot = async () => {
    const data = { ResetType: 'ForceRestart' };
    serverPowerChange(data);
    await checkForServerStatus.bind(this, 'on')();
    setOperationInProgress(false);
    getLastPowerOperationTime();
  };
  const serverSoftPowerOff = async () => {
    const data = { ResetType: 'GracefulShutdown' };
    serverPowerChange(data);
    await checkForServerStatus.bind(this, 'off')();
    setOperationInProgress(false);
    getLastPowerOperationTime();
  };
  const serverHardPowerOff = async () => {
    const data = { ResetType: 'ForceOff' };
    serverPowerChange(data);
    await checkForServerStatus.bind(this, 'off')();
    setOperationInProgress(false);
    getLastPowerOperationTime();
  };
  const serverPowerChange = (data: any) => {
    setOperationInProgress(true);
    api
      .post(
        '/redfish/v1/Systems/system/Actions/ComputerSystem.Reset',
        data,
        undefined,
      )
      .catch((error) => {
        console.log(error);
        setOperationInProgress(false);
      });
  };
  return {
    isOperationInProgress,
    lastPowerOperationTime,
    lastBmcRebootTime,
    setOperationInProgress,
    setLastPowerOperationTime,
    setLastBmcRebootTime,
    getLastPowerOperationTime,
    getLastBmcRebootTime,
    rebootBmc,
    serverPowerOn,
    serverSoftReboot,
    serverHardReboot,
    serverSoftPowerOff,
    serverHardPowerOff,
    serverPowerChange,
  };
});
